// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package cmds

import (
	"fmt"
	"io"

	"gitcode.com/openseaotter/so_proto_gen_go.git/admin_api"
	"gitcode.com/openseaotter/so_server/config"
	"gitcode.com/openseaotter/so_server/utils"
	"github.com/spf13/cobra"
)

var GcCmd_DayBefore uint32
var GcCmd_SkipError bool

var GcCmd = &cobra.Command{
	Use: "gc",
	RunE: func(cmd *cobra.Command, args []string) error {
		cfg, err := config.ReadServerConfig()
		if err != nil {
			return err
		}
		if cfg.SuperToken == "" {
			return fmt.Errorf("miss super token in config")
		}
		conn, err := utils.ConnGrpcServer(fmt.Sprintf("127.0.0.1:%d", cfg.ServicePort))
		if err != nil {
			return err
		}
		defer conn.Close()

		client := admin_api.NewAdminApiClient(conn)

		s, err := client.Gc(cmd.Context(), &admin_api.GcRequest{
			AccessToken: cfg.SuperToken,
			DayBefore:   GcCmd_DayBefore,
			SkipError:   GcCmd_SkipError,
		})
		if err != nil {
			return err
		}
		for {
			res, err := s.Recv()
			if err == io.EOF {
				break
			}
			if err != nil {
				return err
			}
			if res.Code != admin_api.GcResponse_CODE_OK {
				return fmt.Errorf("%s", res.ErrMsg)
			}
			fmt.Println("remove blob", res.RemoveBlobId)
		}
		return nil
	},
}

func init() {
	GcCmd.Flags().Uint32Var(&GcCmd_DayBefore, "dayBefore", 30, "only remove blob create before dayBefore")
	GcCmd.Flags().BoolVar(&GcCmd_SkipError, "skipError", false, "skip error in gc")
}
